/**
 * 
 */
package fluo.desktopserver;

import java.io.File;
import java.util.ArrayList;

/**
 * @author maherbeg
 *
 * Created: Apr 12, 2009
 * Modified: Apr 12, 2009
 */
public class FolderScanner implements Runnable {

	private String folder = "";
	private DesktopServer ds;
	private MP3Filter mp3s;
	private ArrayList<String> curlist;
	
	private int counter=0;
	
	public void run() {
		ds.setMessage("Scanning " + folder + "");
		if(ds.getMusicList().containsKey(folder)){
			ds.setMessage("Folder exists already!");
			if(ds.getDebug())
				System.out.println("DesktopServer.addFolder("+folder+"): Folder has already been added");
			return;
		}
		addFiles(new File(folder));
		ds.addFolder(folder,curlist);
		ds.setMessage("Added " + counter + " files from " + folder);
	}
	
	private void addFiles(File working){
		//TODO Add filtering using MP3 filter
		File[] children = working.listFiles(mp3s);
		if(children != null){
			for(File child : children){
				if(child.isFile()){
					curlist.add(child.toString());
					counter++;
					if((counter % 5) == 0){
						ds.setMessage("Scanning " + folder + "> " + child.toString());
					}
				}
				
				addFiles(child);
			}
		}
	}
	
	public FolderScanner(DesktopServer ds, File folder){
		this.folder = folder.toString();
		this.ds = ds;
		mp3s = new MP3Filter();
		curlist = new ArrayList<String>();
		
		Thread t = new Thread(this);
		t.start();
	}

}
